<template>
    <div>

        <!--        搜索信息区域      -->
        <el-card style="width: 100%; height: 10vh;">
            <el-form :inline="true">
                <el-form-item label="商品名称" label-width="68px">
                    <el-input style="width: 170px" clearable v-model="searchName"
                              placeholder="请输入商品名称"></el-input>
                </el-form-item>

                <el-form-item label="店铺名称" label-width="68px">
                    <el-autocomplete
                            class="inline-input"
                            v-model="searchStoreName"
                            :fetch-suggestions="querySearchStoreName"
                            placeholder="请输入店铺名称"
                            @select="handleSelect"
                            style="width: 200px"
                            clearable
                    ></el-autocomplete>
                </el-form-item>

                <el-form-item label="商品类型" label-width="68px">
                    <el-autocomplete
                            class="inline-input"
                            v-model="searchCategoryName"
                            :fetch-suggestions="querySearchCategoryName"
                            placeholder="请输入商品类型"
                            @select="handleSelect"
                            style="width: 200px"
                            clearable
                    ></el-autocomplete>
                </el-form-item>

                <el-form-item label="状态" label-width="40px">
                    <el-select style="width: 210px" v-model="searchStatus" placeholder="请选择" clearable>
                        <el-option
                                v-for="item in statuss"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-button style="" type="primary" @click="searchByManyCondition" plain> 搜 索
                </el-button>
                <el-button @click="resetCondition"> 重 置</el-button>
            </el-form>
        </el-card>


        <!--           商品信息表格        -->
        <el-card style="width: 100%; ">

            <!--          商品信息    标题-->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold;font-size: 18px">商品信息</span>
                <el-button style="float: right;margin-right: 10px" type="danger" @click="deleteSelectProducts"> 删除选中
                </el-button>
                <el-button style="float: right;margin-right: 20px" type="primary" plain @click="showAddProduct">
                    添加商品
                </el-button>
                <el-button style="float: right;margin-right: 10px" type="primary" plain @click="selectAll"> 查询所有商品
                </el-button>

                <!-- 添加信息的弹窗 -->
                <el-dialog title="添加商品" :visible.sync="dialogVisible_addProduct">
                    <el-form :model="add_product" size="medium" :rules="rules" ref="addProductRef"
                             :validate-on-rule-change="false">

                        <el-form-item prop="name" label="商品名称" label-width="100px">
                            <el-input v-model="add_product.name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>

                        <el-form-item prop="detail" label="商品介绍" label-width="100px">
                            <el-input type="textarea" v-model="add_product.detail" placeholder="请输入店铺介绍"
                                      style="width: 478px;margin-left: 20px"></el-input>
                        </el-form-item>

                        <el-form-item prop="price" label="价格" label-width="100px">
                            <el-input @blur="handlePriceFormat"
                                      v-model="add_product.price" placeholder="请输入价格"
                                      autocomplete="off" type="number"></el-input>
                        </el-form-item>

                        <el-form-item prop="storeName" label="店铺名称" label-width="100px">
                            <el-autocomplete
                                    class="inline-input"
                                    v-model="add_product.storeName"
                                    :fetch-suggestions="querySearchStoreName"
                                    placeholder="请输入店铺名称"
                                    @select="handleSelectAddProductStoreName"
                                    style="width: 600px"
                                    clearable
                            ></el-autocomplete>
                        </el-form-item>

                        <el-form-item prop="categoryName" label="商品类型" label-width="100px">
                            <el-autocomplete
                                    class="inline-input"
                                    v-model="add_product.categoryName"
                                    :fetch-suggestions="querySearchCategoryName"
                                    placeholder="请输入商品类型"
                                    @select="handleSelectAddProductCategoryName"
                                    style="width: 600px"
                                    clearable
                            ></el-autocomplete>
                        </el-form-item>

                        <el-form-item prop="stock" label="库存量" label-width="100px">
                            <el-input v-model="add_product.stock" autocomplete="off"
                                      placeholder="请输入库存量" type="number"></el-input>
                        </el-form-item>

                        <el-form-item prop="sales" label="销量" label-width="100px">
                            <el-input v-model="add_product.sales" autocomplete="off"
                                      placeholder="请输入销量"></el-input>
                        </el-form-item>

                        <el-form-item prop="createTime" label="创建时间" label-width="100px">
                            <el-date-picker
                                    v-model="add_product.createTime"
                                    type="datetime"
                                    placeholder="选择日期时间"
                                    align="right"
                                    :picker-options="pickerOptions">
                            </el-date-picker>
                        </el-form-item>

                        <el-form-item prop="updateTime" label="更新时间" label-width="100px">
                            <el-date-picker
                                    v-model="add_product.updateTime"
                                    type="datetime"
                                    placeholder="选择日期时间"
                                    align="right"
                                    :picker-options="pickerOptions">
                            </el-date-picker>
                        </el-form-item>

                        <el-form-item prop="image" label="商品图片" label-width="100px">
                            <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                <el-avatar shape="square" :size="200" fit="fill"
                                           :src="add_product.image"></el-avatar>
                                <el-upload
                                        :show-file-list="false"
                                        :action="$baseUrl + '/file/upload'"
                                        :on-success="handleFileUploadImage"
                                        style="margin-left: 50px"
                                >
                                    <el-button type="primary">上传商品图片</el-button>
                                </el-upload>

                            </div>

                        </el-form-item>

                        <el-form-item prop="detailImg" label="介绍图片" label-width="100px">

                            <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                <el-image
                                        style="width: 200px; height: 200px;background-color: #c0c4cc;border-radius: 5px"
                                        :src="add_product.detailImg"
                                        :preview-src-list="detailImgList">
                                    <div slot="error" class="image-slot">
                                    </div>
                                </el-image>

                                <el-upload
                                        :show-file-list="false"
                                        :action="$baseUrl + '/file/upload'"
                                        :on-success="handleFileUploadDetailImg"
                                        style="margin-left: 50px"
                                >
                                    <el-button type="primary">上传商品介绍图片</el-button>
                                </el-upload>

                            </div>

                            <!--                            <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                                            <el-avatar shape="square" :size="200" fit="fill"
                                                                       :src="add_product.detailImg"></el-avatar>
                                                            <el-upload
                                                                    :show-file-list="false"
                                                                    :action="$baseUrl + '/file/upload'"
                                                                    :on-success="handleFileUploadDetailImg"
                                                                    style="margin-left: 50px"
                                                            >
                                                                <el-button type="primary">上传商品介绍图片</el-button>
                                                            </el-upload>

                                                        </div>-->

                        </el-form-item>

                        <el-form-item prop="status" label="状态" label-width="100px">
                            <el-select v-model="add_product.status" placeholder="请选择状态">
                                <el-option
                                        v-for="item in statuss"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>

                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button type="warning" @click="resetAddProduct"> 重 置</el-button>
                        <el-button @click="cancelDialog_addProduct"> 取 消</el-button>
                        <el-button type="primary" @click="handleEdit_addProduct"> 确 定</el-button>
                    </div>

                </el-dialog>

                <!-- 删除商品信息的弹窗 -->
                <el-dialog
                        title="提示"
                        :visible.sync="dialogVisible_deleteSelect"
                        width="30%">
                    <span>真的要删除选中的所有信息吗？</span>
                    <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible_deleteSelect = false">取 消</el-button>
                                    <el-button type="danger" @click="handleDeleteProducts">确 定</el-button>
                                </span>
                </el-dialog>

            </div>


            <!--     商品信息列表    展示-->
            <template>
                <el-table height="410"
                          :header-cell-style="{fontSize: '14px','text-align':'center'}"
                          :cell-style="{'text-align':'center'}"
                          :data="products"
                          @selection-change="handleSelectCodeForTicket"
                          stripe
                          style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column width="50" label="序号" type="index" align="center"></el-table-column>

                    <el-table-column prop="name" label="商品名称" show-overflow-tooltip
                                     width="120px"></el-table-column>
                    <el-table-column prop="price" label="价格" width="50px" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="category.name" label="商品类型" width="100px"
                                     show-overflow-tooltip></el-table-column>
                    <el-table-column prop="store.name" label="商家名称" show-overflow-tooltip
                                     width="100px"></el-table-column>
                    <el-table-column prop="detail" label="商品介绍" show-overflow-tooltip
                                     width="180px"></el-table-column>
                    <el-table-column prop="stock" label="库存" show-overflow-tooltip width="50px"></el-table-column>
                    <el-table-column prop="sales" label="销量" show-overflow-tooltip width="50px"></el-table-column>
                    <el-table-column label="状态" width="80">
                        <template slot-scope="scope">
                            <!--    状态：0.下架；1.上架；2.缺货；3.预售；4.售罄；5.限时特惠  6.待审核       -->
                            <el-tag type="danger" effect="dark" v-if="scope.row.status==0">已下架</el-tag>
                            <el-tag type="success" effect="dark" v-if="scope.row.status==1">上架中</el-tag>
                            <el-tag type="warning" effect="dark" v-if="scope.row.status==2">缺货中</el-tag>
                            <el-tag type="warning" v-if="scope.row.status==3">预售中</el-tag>
                            <el-tag type="danger" v-if="scope.row.status==4">已售罄</el-tag>
                            <el-tag type="success" v-if="scope.row.status==5">限时特惠</el-tag>
                            <el-tag type="info" effect="dark" v-if="scope.row.status==6">待审核</el-tag>
                        </template>
                    </el-table-column>

                    <!--      图片显示    -->
                    <el-table-column prop="image" label="图片" width="150px">
                        <template slot-scope="scope">
                            <el-avatar shape="square" :size="100" fit="fill" :src="scope.row.image"></el-avatar>
                        </template>
                    </el-table-column>

                    <el-table-column label="审核状态" width="78px">

                        <template slot-scope="scope">
                            <el-button v-if="scope.row.status===6"
                                       size="mini" type="primary" plain
                                       @click="passProduct(scope.row)">通过
                            </el-button>
                            <el-tag v-if="scope.row.status!==6" type="success">已通过</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作">

                        <!--          编辑  +  删除   商品-->
                        <template slot-scope="scope">

                            <!--    查看详情    -->
                            <!--    查看详情按钮    -->
                            <router-link style="margin: 0 10px"
                                         :to="{ path: '/manager/productInfo',  query: { id: scope.row.id } }">
                                <el-button icon="el-icon-search" circle></el-button>
                            </router-link>

                            <!--                                            编辑按钮    -->
                            <el-button type="primary" icon="el-icon-edit" circle
                                       @click="handleEditButton(scope.row)"></el-button>
                            <!--                                            删除按钮    -->
                            <el-button type="danger" icon="el-icon-delete" circle
                                       @click="handleDeleteButton(scope.row)"></el-button>


                            <!-- 删除商品信息的弹窗 -->
                            <el-dialog
                                    title="提示"
                                    :visible.sync="dialogVisible_delete"
                                    width="30%">
                                <span style="display: flex;">真的要删除这条信息吗？</span>
                                <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible_delete = false">取 消</el-button>
                                    <el-button type="danger" @click="handleDeleteProduct">确 定</el-button>
                                </span>
                            </el-dialog>


                            <!-- 编辑信息的弹窗 -->
                            <el-dialog title="修改商品信息" :visible.sync="dialogFormVisible_edit">
                                <el-form :model="edit_product" size="medium" :rules="rules" ref="editProductRef"
                                         :validate-on-rule-change="false">

                                    <el-form-item prop="name" label="商品名称" label-width="100px">
                                        <el-input v-model="edit_product.name" placeholder="请输入商品名称"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="detail" label="商品介绍" label-width="100px">
                                        <el-input type="textarea" v-model="edit_product.detail"
                                                  placeholder="请输入店铺介绍"
                                                  style="width: 478px;margin-left: 20px"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="price" label="价格" label-width="100px">
                                        <el-input @blur="handlePriceFormat"
                                                  v-model="edit_product.price" placeholder="请输入价格"
                                                  autocomplete="off" type="number"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="storeName" label="店铺名称" label-width="100px">
                                        <el-autocomplete
                                                class="inline-input"
                                                v-model="edit_product.storeName"
                                                :fetch-suggestions="querySearchStoreName"
                                                placeholder="请输入店铺名称"
                                                @select="handleSelectEditProductStoreName"
                                                style="width: 600px"
                                                clearable
                                        ></el-autocomplete>
                                    </el-form-item>

                                    <el-form-item prop="categoryName" label="商品类型" label-width="100px">
                                        <el-autocomplete
                                                class="inline-input"
                                                v-model="edit_product.categoryName"
                                                :fetch-suggestions="querySearchCategoryName"
                                                placeholder="请输入商品类型"
                                                @select="handleSelectEditProductCategoryName"
                                                style="width: 600px"
                                                clearable
                                        ></el-autocomplete>
                                    </el-form-item>

                                    <el-form-item label="库存量" label-width="100px">
                                        <el-input v-model="edit_product.stock" autocomplete="off"
                                                  placeholder="请输入库存量" type="number"></el-input>
                                    </el-form-item>

                                    <el-form-item label="销量" label-width="100px">
                                        <el-input v-model="edit_product.sales" autocomplete="off"
                                                  placeholder="请输入销量" type="number"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="createTime" label="创建时间" label-width="100px">
                                        <el-date-picker
                                                v-model="edit_product.createTime"
                                                type="datetime"
                                                placeholder="选择日期时间"
                                                align="right"
                                                :picker-options="pickerOptions">
                                        </el-date-picker>
                                    </el-form-item>

                                    <el-form-item prop="updateTime" label="更新时间" label-width="100px">
                                        <el-date-picker
                                                v-model="edit_product.updateTime"
                                                type="datetime"
                                                placeholder="选择日期时间"
                                                align="right"
                                                :picker-options="pickerOptions">
                                        </el-date-picker>
                                    </el-form-item>

                                    <el-form-item prop="image" label="商品图片" label-width="100px">
                                        <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                            <el-avatar shape="square" :size="200" fit="fill"
                                                       :src="edit_product.image"></el-avatar>
                                            <el-upload
                                                    :show-file-list="false"
                                                    :action="$baseUrl + '/file/upload'"
                                                    :on-success="handleFileUploadImage"
                                                    style="margin-left: 50px"
                                            >
                                                <el-button type="primary">上传商品图片</el-button>
                                            </el-upload>

                                        </div>

                                    </el-form-item>

                                    <el-form-item prop="detailImg" label="介绍图片" label-width="100px">

                                        <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                            <el-image
                                                    style="width: 200px; height: 200px;background-color: #c0c4cc;border-radius: 5px"
                                                    :src="edit_product.detailImg"
                                                    :preview-src-list="detailImgList">
                                                <div slot="error" class="image-slot">
                                                </div>
                                            </el-image>

                                            <el-upload
                                                    :show-file-list="false"
                                                    :action="$baseUrl + '/file/upload'"
                                                    :on-success="handleFileUploadDetailImg"
                                                    style="margin-left: 50px"
                                            >
                                                <el-button type="primary">上传商品介绍图片</el-button>
                                            </el-upload>

                                        </div>

                                        <!--                            <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                                                        <el-avatar shape="square" :size="200" fit="fill"
                                                                                   :src="add_product.detailImg"></el-avatar>
                                                                        <el-upload
                                                                                :show-file-list="false"
                                                                                :action="$baseUrl + '/file/upload'"
                                                                                :on-success="handleFileUploadDetailImg"
                                                                                style="margin-left: 50px"
                                                                        >
                                                                            <el-button type="primary">上传商品介绍图片</el-button>
                                                                        </el-upload>

                                                                    </div>-->

                                    </el-form-item>

                                    <el-form-item prop="status" label="状态" label-width="100px">
                                        <el-select v-model="edit_product.status" placeholder="请选择状态"
                                                   style="float: left;margin-left: 50px">
                                            <el-option
                                                    v-for="item in statuss"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>


                                </el-form>


                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="cancelDialog_editProduct">取 消</el-button>
                                    <el-button type="primary" @click="handleEdit">确 定</el-button>
                                </div>

                            </el-dialog>
                        </template>
                    </el-table-column>


                </el-table>
            </template>

            <el-pagination
                    style="float: right;margin: 20px 0"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    background
                    :total="total">
            </el-pagination>
        </el-card>

    </div>
</template>

<script>

import crypto from "@/utils/encryp";
import dateUtil from '@/utils/dateUtil'

export default {
    name: 'Product',
    data() {
        // 金额验证
        const validatePrice = (rule, value, callback) => {
            if (!value) {
                callback(new Error("价格不能为空"));
            } else if (value.split(".").length > 2) {
                callback(new Error("输入正确格式的金额")); //防止输入多个小数点
            } else {
                callback();
            }
        };

        return {
            dialogFormVisible_edit: false,      // 编辑按钮弹出框
            dialogVisible_delete: false,        // 删除按钮弹出框
            dialogVisible_deleteSelect: false,  // 选中删除按钮弹出框
            dialogVisible_addProduct: false,      // 添加商品按钮弹出框

            productId: '',             // 存储被删除商品的id
            ids: [],                 // 存储被选中商品的id
            products: [],              // 存储商品信息

            edit_product: {},          // 存储当前操作的商品
            edit_product_temp: {},     // 存储当前操作的商品
            add_product: {
                status: []
            },                       // 存储添加的商品信息
            avatarUrl: '',           // 暂存后台传回来的图片链接

            searchName: '',      // 存储搜索的商品名
            searchStoreName: '',     // 存储搜索的店铺名
            searchCategoryName: '',      // 存储搜索的商品类别
            searchStatus: '',       // 存储搜索的状态
            // 状态：0.下架；1.上架；2.缺货；3.预售；4.售罄；5.限时特惠  6.待审核
            statuss: [{             // 存储所有状态
                value: 0,
                label: '已下架'
            }, {
                value: 1,
                label: '上架中'
            }, {
                value: 2,
                label: '缺货中'
            }, {
                value: 3,
                label: '预售中'
            }, {
                value: 4,
                label: '已售罄'
            }, {
                value: 5,
                label: '限时特惠'
            }, {
                value: 6,
                label: '待审核'
            }],
            categoryRestaurants: [],          // 存储所有所有商品分类
            storeRestaurants: [],          // 存储所有所有商家名称

            detailImgList: [],              // 大图预览
            currentPage: 1,          // 当前页码
            pageSizes: [5, 10, 50, 100], // 每页显示条数
            pageSize: 5,             // 每页显示条数
            total: 0,                // 商品总数

            // 输入校验规则
            rules: {
                name: [
                    {required: true, message: '请输入商品名称', trigger: 'blur'},
                    {min: 2, message: '账号最少为2个字符', trigger: 'blur'}
                ],
                detail: [
                    {required: true, message: '请填写商品介绍', trigger: 'blur'}
                ],
                price: [
                    {required: true, validator: validatePrice, trigger: "change"}
                ],
                storeName: [
                    {required: true, message: '请输入商店名称', trigger: 'change', maxlength: 50}
                ],
                categoryName: [
                    {required: true, message: '请输入商品类型', trigger: 'change', maxlength: 50}
                ],
                stock: [
                    {required: true, message: '请输入库存', trigger: 'blur', maxlength: 12}
                ],
                sales: [
                    {required: false, message: '请输入销量', trigger: 'blur', maxlength: 12}
                ],
                createTime: [
                    {required: true, message: '请输入创建时间', trigger: 'blur'}
                ],
                updateTime: [
                    {required: true, message: '请输入更新时间', trigger: 'blur'}
                ],
                image: [
                    {required: true, message: '请上传图片', trigger: 'blur'}
                ],
                detailImg: [
                    {required: true, message: '请上传图片', trigger: 'blur'}
                ],
                status: [
                    {required: true, message: '请选择状态', trigger: 'change'}
                ],
            },

            // 时间选择
            pickerOptions: {
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },

        }
    },
    mounted() {
        // this.$request.get('/product/selectByPage?currentPage=1&pageSize=5').then(res => {
        //     if (res.code === '200') {
        //         this.products = res.data.list;
        //         this.total = res.data.total;
        //     } else {
        //         this.$message.error(res.msg);
        //     }
        // })
        this.searchByManyConditionNoMsg()

        // 加载所有类目
        this.loadAllCategory()
        this.loadAllStore()
    },

    methods: {

        passProduct(product) {
            product.status = 1
            console.log(product)
            this.$request.post('/product/update', product).then(res => {
                if (res.code === '200') {
                    this.$message.success('审核通过')
                    this.searchByManyConditionNoMsg()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        // 输入建议的查询函数
        querySearchCategoryName(queryString, cb) {
            var restaurants = this.categoryRestaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        querySearchStoreName(queryString, cb) {
            var restaurants = this.storeRestaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        // 加载所有的商品分类
        loadAllCategory() {
            this.$request.get('/category/loadAllCategory').then(res => {
                if (res.code === '200') {
                    this.categoryRestaurants = res.data;
                    // 遍历restaurants,让this.restaurants中的数据格式化name参数变为value
                    this.categoryRestaurants.forEach((restaurant) => {
                        restaurant.value = restaurant.name;
                        // delete restaurant.name;
                    });
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        // 加载所有的店铺
        loadAllStore() {
            this.$request.get('/store/loadAllStore').then(res => {
                if (res.code === '200') {
                    this.storeRestaurants = res.data;
                    // 遍历restaurants,让this.restaurants中的数据格式化name参数变为value
                    this.storeRestaurants.forEach((restaurant) => {
                        restaurant.value = restaurant.name;
                        // delete restaurant.name;
                    });
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        // 带搜索建议的输入框被选中后的响应函数
        handleSelect(item) {
            // console.log(item);
        },
        // 处理添加商品时，对店铺Id的更新
        handleSelectAddProductStoreName(item) {
            this.add_product.storeId = item.id;
        },
        // 处理添加商品时，对分类Id的更新
        handleSelectAddProductCategoryName(item) {
            this.add_product.categoryId = item.id;
        },
        // 处理添加商品时，对店铺Id的更新
        handleSelectEditProductStoreName(item) {
            this.edit_product.storeId = item.id;
        },
        // 处理添加商品时，对分类Id的更新
        handleSelectEditProductCategoryName(item) {
            this.edit_product.categoryId = item.id;
        },
        // 移除表单的校验
        clearcheck(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate()
            }
        },

        // 查询所有商品
        selectAll() {
            this.$request.get('/product/selectByPage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize).then(res => {
                if (res.code === '200') {
                    this.products = res.data.list;
                    this.total = res.data.total;
                    this.$message.success('查询成功');
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 添加商品
        handleEdit_addProduct() {
            // 格式化时间
            this.add_product.createTime = dateUtil.formatDate(this.add_product.createTime)
            this.add_product.updateTime = dateUtil.formatDate(this.add_product.updateTime)
            // 输入检验
            this.$refs['addProductRef'].validate((valid) => {
                if (valid) {
                    this.avatarUrl = ''
                    // 校验通过
                    // 添加商品
                    this.$request.post('/product/addProduct', this.add_product).then(res => {
                        this.dialogVisible_addProduct = false;
                        this.add_product = {}
                        if (res.code === '200') {
                            this.$message.success('添加成功')
                            this.searchByManyConditionNoMsg()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        },

        // 处理价格格式
        handlePriceFormat() {
            this.add_product.price = parseFloat(this.add_product.price).toFixed(2)
            this.edit_product.price = parseFloat(this.edit_product.price).toFixed(2)
        },

        // 取消添加商品
        cancelDialog_addProduct() {
            this.avatarUrl = ''
            this.dialogVisible_addProduct = false;
        },

        // 重置添加的信息
        resetAddProduct() {
            this.add_product = {}
            this.avatarUrl = ''
        },

        // 显示添加商品的弹出框
        showAddProduct() {
            this.clearcheck('addProductRef')
            this.dialogVisible_addProduct = true;
            this.avatarUrl = ''
            this.add_product = {}
            this.detailImgList = []
        },

        // 删除选中二次确认
        handleDeleteProducts() {
            this.dialogVisible_deleteSelect = false;
            if (this.ids.length > 0) {
                // 删除选中
                this.$request.post('/product/deleteByIds', this.ids).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功');
                        // 刷新数据
                        this.searchByManyConditionNoMsg()
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$message.info('请选择要删除的商品');
            }
        },

        // 删除选中二次提醒
        deleteSelectProducts() {
            // 显示二次提醒弹窗
            this.dialogVisible_deleteSelect = true;
        },

        // 获取选中的商品id，
        // 并存储到 ids 数组中
        handleSelectCodeForTicket(val) {
            this.ids = val.map((item) => item.id);
        },


        // currentPage 改变时会触发
        handleCurrentChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.currentPage = val;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },


        //  pageSize 改变时会触发
        handleSizeChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.pageSize = val;
            this.currentPage = 1;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },


        // 条件查询
        searchByManyCondition() {
            // 如果状态未选择的话，调用A接口
            // 否则调用B接口
            // A接口不包括状态参数
            // B接口包括状态参数/product
            if (this.searchStatus !== '' && this.searchStatus !== null && this.searchStatus !== undefined) {
                // 如果searchStatus的值不为空，则将其转换为整数
                this.searchStatus = parseInt(this.searchStatus)
                this.$request.get('/product/selectByManyConditionInpage?currentPage=' + this.currentPage
                    + '&pageSize=' + this.pageSize
                    + '&name=' + this.searchName
                    + '&storeName=' + this.searchStoreName
                    + '&categoryName=' + this.searchCategoryName
                    + '&status=' + this.searchStatus).then(res => {
                    if (res.code === '200') {
                        this.products = res.data.list
                        this.total = res.data.total
                        this.$message.success("查询成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$request.get('/product/selectByManyConditionNoStatusInpage?currentPage=' + this.currentPage
                    + '&pageSize=' + this.pageSize
                    + '&name=' + this.searchName
                    + '&storeName=' + this.searchStoreName
                    + '&categoryName=' + this.searchCategoryName).then(res => {
                    if (res.code === '200') {
                        this.products = res.data.list
                        this.total = res.data.total
                        this.$message.success("查询成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            }


        },

        // 条件查询 用来刷新数据不提示
        searchByManyConditionNoMsg() {
            // 如果状态未选择的话，调用A接口
            // 否则调用B接口
            // A接口不包括状态参数
            // B接口包括状态参数/product
            if (this.searchStatus !== '' && this.searchStatus !== null && this.searchStatus !== undefined) {
                // 如果searchStatus的值不为空，则将其转换为整数
                this.searchStatus = parseInt(this.searchStatus)
                this.$request.get('/product/selectByManyConditionInpage?currentPage=' + this.currentPage
                    + '&pageSize=' + this.pageSize
                    + '&name=' + this.searchName
                    + '&storeName=' + this.searchStoreName
                    + '&categoryName=' + this.searchCategoryName
                    + '&status=' + this.searchStatus).then(res => {
                    if (res.code === '200') {
                        this.products = res.data.list
                        this.total = res.data.total
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$request.get('/product/selectByManyConditionNoStatusInpage?currentPage=' + this.currentPage
                    + '&pageSize=' + this.pageSize
                    + '&name=' + this.searchName
                    + '&storeName=' + this.searchStoreName
                    + '&categoryName=' + this.searchCategoryName).then(res => {
                    if (res.code === '200') {
                        this.products = res.data.list
                        this.total = res.data.total
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            }
        },

        // 分页查找
        selectByPage() {
            this.$request.get('/product/selectByPage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize).then(res => {
                if (res.code === '200') {
                    this.products = res.data.list
                    this.total = res.data.total
                } else {
                    this.$message.error(res.msg);
                }
            })
        },


        // 重置搜索条件
        resetCondition() {
            this.searchName = ''
            this.searchStoreName = ''
            this.searchCategoryName = ''
            this.searchStatus = ''
            this.currentPage = 1
            this.pageSize = 5
            // 刷新获取商品信息
            this.$request.get('/product/selectByPage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize).then(res => {
                if (res.code === '200') {
                    this.products = res.data.list
                    this.total = res.data.total
                    this.$message.success("重置成功")
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 处理 图片上传按钮   的点击事件
        handleFileUpload(response, file, fileList) {
            // 判断上传的文件的类型
            // 只能上传图片类型，如果不是图片资源那么提示“只能上传图片！！”
            if (!file.raw.type.includes('image')) {
                this.$message.error('只能上传图片！')
                return
            }
            if (response.data) {
                // 数据解密
                let key = "dianzishumaMall0"; //加密密钥
                let iv = "dianzishumaMall0"; //加密aesIV，偏移量

                const data = crypto.decryptAES(response.data, key, iv)
                response.data = JSON.parse(data)
            }
            //  1. 获取上传成功后返回的图片地址
            let url = response.data;
            // 2. 修改表单中对应的字段值
            this.avatarUrl = url;
            this.add_product.avatar = url
            this.edit_product.avatar = url
            // 刷新图片信息
            this.$forceUpdate()
        },

        // 处理 商品图片上传按钮   的点击事件
        handleFileUploadImage(response, file, fileList) {
            // 判断上传的文件的类型
            // 只能上传图片类型，如果不是图片资源那么提示“只能上传图片！！”
            if (!file.raw.type.includes('image')) {
                this.$message.error('只能上传图片！')
                return
            }

            if (response.data) {
                // 数据解密
                let key = "dianzishumaMall0"; //加密密钥
                let iv = "dianzishumaMall0"; //加密aesIV，偏移量

                const data = crypto.decryptAES(response.data, key, iv)
                response.data = JSON.parse(data)
            }
            //  1. 获取上传成功后返回的图片地址
            let url = response.data;
            // 2. 修改表单中对应的字段值
            this.add_product.image = url
            this.edit_product.image = url
            // 刷新图片信息
            this.$forceUpdate()
        },

        // 处理 商品图片上传按钮   的点击事件
        handleFileUploadDetailImg(response, file, fileList) {

            // 判断上传的文件的类型
            // 只能上传图片类型，如果不是图片资源那么提示“只能上传图片！！”
            if (!file.raw.type.includes('image')) {
                this.$message.error('只能上传图片！')
                return
            }
            if (response.data) {
                // 数据解密
                let key = "dianzishumaMall0"; //加密密钥
                let iv = "dianzishumaMall0"; //加密aesIV，偏移量

                const data = crypto.decryptAES(response.data, key, iv)
                response.data = JSON.parse(data)
            }
            //  1. 获取上传成功后返回的图片地址
            let url = response.data;
            // 2. 修改表单中对应的字段值
            this.add_product.detailImg = url
            this.edit_product.detailImg = url
            this.detailImgList.push(url)
            // 刷新图片信息
            this.$forceUpdate()
        },

        // 显示 修改商品信息    弹窗
        handleEditButton(product) {
            this.detailImgList = []
            this.detailImgList.push(product.detailImg)

            this.clearcheck('editProductRef')
            // 将当前行的商品数据传入form中
            this.edit_product = JSON.parse(JSON.stringify(product));
            this.edit_product_temp = JSON.parse(JSON.stringify(product));

            // 店铺名称、分类名称转化
            this.edit_product.storeName = this.edit_product.store.name
            this.edit_product.categoryName = this.edit_product.category.name
            this.handlePriceFormat()

            // 显示弹窗
            this.dialogFormVisible_edit = true;
        },

        // 删除按钮二次提醒
        handleDeleteButton(product) {
            this.dialogVisible_delete = true
            this.productId = product.id
        },


        // 删除当前商品
        handleDeleteProduct() {
            this.dialogVisible_delete = false;
            this.$request.delete('/product/deleteById/' + this.productId).then(res => {
                if (res.code === '200') {
                    this.$message.success('删除成功');
                    this.productId = ''
                    // 重新加载数据
                    this.searchByManyConditionNoMsg()
                } else {
                    this.$message.error(res.msg);
                }
            })
        },


        // 取消修改信息
        cancelDialog_editProduct() {
            this.dialogFormVisible_edit = false;
            this.edit_product = {}
            this.avatarUrl = ''
        },


        // 修改商品信息
        handleEdit() {
            console.log(this.edit_product)

            // 格式化时间
            // 如果时间没变不处理
            if (this.edit_product.createTime !== this.edit_product_temp.createTime) {
                this.edit_product.createTime = dateUtil.formatDate(this.edit_product.createTime)
            }
            if (this.edit_product.updateTime !== this.edit_product_temp.updateTime) {
                this.edit_product.updateTime = dateUtil.formatDate(this.edit_product.updateTime)
            }
            // 输入检验
            this.$refs['editProductRef'].validate((valid) => {
                if (valid) {
                    // 校验通过
                    this.$request.put('/product/updateById', this.edit_product).then(res => {
                        this.dialogFormVisible_edit = false;
                        // console.log(res)
                        if (res.code === '200') {
                            this.$message.success('修改成功');
                            this.edit_product = {}
                            this.avatarUrl = ''
                            // 重新加载数据
                            this.searchByManyConditionNoMsg()
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        }
    }
}
</script>


<style>
.el-dialog__body {
    padding: 10px 30px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

input[type="number"] {
    -moz-appearance: textfield;
}


</style>